package tw.com.softleader.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import tw.com.softleader.spring.entity.Book;

@Repository
public class BookDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public List<Book> findAll(){
//		Session session = sessionFactory.openSession();
		Session session = sessionFactory.getCurrentSession();
		List<Book> lists = session.createCriteria(Book.class).list();
//		session.close();
		return lists;
	}
	
	public Book findOne(Long id){
//		Session session = sessionFactory.openSession();
		Session session = sessionFactory.getCurrentSession();
//		Transaction tx = session.beginTransaction();
		Book book = (Book) session.get(Book.class, id);
//		tx.commit();
//		session.close();
		return book;
	}
	
	
	public void insert(Book book){
//		Session session = sessionFactory.openSession();
		Session session = sessionFactory.getCurrentSession();
//		Transaction tx = session.beginTransaction();
		session.persist(book);
//		tx.commit();
//		session.close();
	} 
	
	public void update(Book book){
//		Session session = sessionFactory.openSession();
		Session session = sessionFactory.getCurrentSession();
//		Transaction tx = session.beginTransaction();
		session.merge(book);
//		tx.commit();
//		session.close();
	} 
	
	public void delete(Long id){
		Book book = new Book();
		book.setId(id);
//		Session session = sessionFactory.openSession();
		Session session = sessionFactory.getCurrentSession();
//		Transaction tx = session.beginTransaction();
		session.delete(book);
//		tx.commit();
//		session.close();
	} 


}
